package com.dt.record

import android.app.AlertDialog
import android.app.ListActivity
import android.content.Intent
import android.database.Cursor
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.*
import androidx.annotation.Nullable
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.DialogUIUtils.showToast
import com.dou361.dialogui.listener.DialogUIListener
import kotlinx.android.synthetic.main.activity_file_browser_acitivity.*
import kotlinx.android.synthetic.main.file_item.view.*
import java.io.File


class FileManage(fullWin: MainActivity) {
    private val mfullWin=fullWin
    private var videoDir="/CCTV"
    private val VIDEO_URI: Uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI //视频频文件的URI,


    private fun showFileList(){

    }

    init{
        val cr = mfullWin.contentResolver
        //ContentProvider只能由ContentResolver发送请求
        //获取音频文件的URI,
        //音频 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
        //视频 MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        //图片MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val columns = arrayOf(MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA)
        //要读的列名,这些常量可以查GOOGLE官方开发文档,TITLE是标题 DATA是路径
        val cursor: Cursor? = cr.query(
            VIDEO_URI,
            columns,
            MediaStore.Video.Media.DURATION + ">?",
            arrayOf("3000"),//视频文件时长
            null
        )

//        val uri = Uri.parse("content://com.DT.provider/storage/emulated/0/CCTV/news.mp4")
//        Log.i("file_manage", cursor.toString())
        //跟查询SQL一样了,除了第一个参数不同外.后面根据时长过滤小于10秒的文件
        while (cursor?.moveToNext()!!) {
            //循环读取第一列,即文件路径,0列是标题
            Log.i("file_manage", cursor.getString(1))

            val newtext=TextView(fullWin)
            newtext.text=cursor.getString(1)
//            fullWin.list_layout.addView(newtext)


            val file = File(videoDir, "news.mp4")
//            Log.i("file_manage",Environment.getExternalStorageDirectory().path)
            if (!file.exists()) {
//                Toast.makeText(mVideoView.context, "视频不存在", Toast.LENGTH_SHORT).show()
                //              mfullWin.finish() //释放当前activity,在下一个activity按下返回键不会回到当前activity,直接跳到此activity的上一个activity

            }
//            val uri = FileProvider.getUriForFile(mfullWin, "com.DT.provider", file)
//            mVideoView.setVideoPath(uri.toString()) //设置视频文件
        }
        cursor.close()
    }
}


class FileBrowserActivity : ListActivity() {
    private var rootPath: String? = null
    private var pathFlag = false
    private var pathList: List<String>? = null
    private var itemsList: List<String>? = null
    private var curPathTextView: TextView? = null
    private var checkCount=0

    var MID = 0
    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_file_browser_acitivity)

        /**设置沉浸式主题*/
        if (Build.VERSION.SDK_INT >= 21) {

            var decorView = getWindow().getDecorView()
            var option = (
                    View.SYSTEM_UI_FLAG_LOW_PROFILE or
                            View.SYSTEM_UI_FLAG_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or

                            View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or
                            View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR )

            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT)
        }

        initView()
        initInfo()
        ItemOnLongClick()
    }

    private fun initInfo() {
        pathFlag = intent.getBooleanExtra("area", false)
        rootPath = getRootPath()+"/CCTV"
        if (rootPath == null) {
            Toast.makeText(this, "所选SD卡为空！", Toast.LENGTH_SHORT).show()
            finish()
        } else {
            getFileDir(rootPath!!)
        }
    }

    private fun initView() {
        curPathTextView = findViewById<View>(R.id.curPath) as TextView
    }

    fun back(view: View){
        Log.i("test", "touch back")
    }

    private fun getFileDir(filePath: String) {
        curPathTextView!!.text = filePath
        itemsList = ArrayList()
        pathList = ArrayList()
        val file = File(filePath)
        val files = file.listFiles()
        if (filePath != rootPath) {
            (itemsList as ArrayList<String>).add("b1")
            (pathList as ArrayList<String?>).add(rootPath)
            (itemsList as ArrayList<String>).add("b2")
            (pathList as ArrayList<String?>).add(file.parent)
        }
        if (files == null) {
            Toast.makeText(this, "所选SD卡为空！", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        for (i in files.indices) {//逐个文件更新
            val f = files[i]
            // if (checkSpecificFile(f)) {
            (itemsList as ArrayList<String>).add(f.name)
            (pathList as ArrayList<String?>).add(f.path)
            //   }
        }
        listAdapter = MyAdapter(this, itemsList as ArrayList<String>, pathList as ArrayList<String>)
    }

    fun checkSpecificFile(file: File): Boolean {
        val fileNameString = file.name
        val endNameString = fileNameString.substring(
            fileNameString.lastIndexOf(".") + 1, fileNameString.length
        )
            .toLowerCase()
        Log.d(TAG, "checkShapeFile: $endNameString")
        if (file.isDirectory) {
            return true
        }
        return if (endNameString == "txt") {
            true
        } else {
            false
        }
    }

    private fun getRootPath(): String? {
        return try {
            var rootPath: String?
            if (pathFlag) {
                Log.d(TAG, "getRootPath: 正在获取内置SD卡根目录")
                rootPath = Environment.getExternalStorageDirectory()
                    .toString()
                Log.d(
                    TAG,
                    "getRootPath: 内置SD卡目录为:$rootPath"
                )
                rootPath
            } else {
                Log.d(TAG, "getRootPath: 正在获取外置SD卡根目录")
                rootPath = System.getenv("SECONDARY_STORAGE")
                if (rootPath == Environment.getExternalStorageDirectory().toString()) rootPath =
                    null
                Log.d(
                    TAG,
                    "getRootPath:  外置SD卡路径为：$rootPath"
                )
                rootPath
            }
        } catch (e: Exception) {
            Log.e("getRootPath", e.toString())
            null
        }
    }
    fun test(view: View){
        val textview=view as TextView
        Log.i("test", textview.text.toString())

//        textview.parent.parent

    }

    override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
        if(v.check.visibility == View.VISIBLE){             // 列表多选
            v.check.performClick()//模拟点击checkbox
        }
        else{                                               // 列表单选
            if(v.text.text == ".." || v.text.text == "/")   // 点击返回上级目录时候清楚多选
                clearCheck(v)
            val file = File(pathList!![position])
            if (file.isDirectory) {
                getFileDir(file.path)

            } else {
                val data = Intent(this@FileBrowserActivity, MainActivity::class.java)
                val bundle = Bundle()
                bundle.putString("file", file.path)
                data.putExtras(bundle)
                setResult(2, data)
                finish()
            }
        }
    }

    private fun ItemOnLongClick() {
        listView.setOnItemLongClickListener(AdapterView.OnItemLongClickListener { arg0, arg1, arg2, arg3 ->
            // 做长按以后的事情
            file_menu.visibility = View.VISIBLE
            arg1.check.visibility = View.GONE
//            arg0.checkBox.visibility
            checkTitle.visibility = View.VISIBLE
            curPath.visibility = View.GONE

            (listAdapter as MyAdapter).showCheck(true)
            (listAdapter as MyAdapter).notifyDataSetChanged()
            arg1.check.performClick()

            true
        })
    }

    fun checkboxClick(view: View){
      if( (view as CheckBox).isChecked){
          checkCount++
          titleCount.text="已选中"+checkCount+"项"
      }else{
          checkCount--
          titleCount.text="已选中"+checkCount+"项"
      }
    }


    fun clearCheck(view: View){
        file_menu.visibility=View.GONE
        checkTitle.visibility=View.GONE
        curPath.visibility=View.VISIBLE
        (listAdapter as MyAdapter).showCheck(false)
        (listAdapter as MyAdapter).notifyDataSetChanged()
        checkCount=0
    }

    fun allCkeckClick(view: View){
        view as TextView
        if(view.text == "全不选") {
            (listAdapter as MyAdapter).setAllCheck(2)
            (listAdapter as MyAdapter).notifyDataSetChanged()
            view.text = "全选"
        }
        else if(view.text == "全选") {
            (listAdapter as MyAdapter).setAllCheck(1)
            (listAdapter as MyAdapter).notifyDataSetChanged()
            view.text = "全不选"
        }
        checkCount=(listAdapter as MyAdapter).getCheckboxCount()
        titleCount.text="已选中"+(listAdapter as MyAdapter).getCheckboxCount()+"项"

        Log.i("getCount()", "" + (listAdapter as MyAdapter).getCount())

    }

    /**
     * 获取listView中item的布局
     * @param pos 位置
     * @param listView listView
     * @return
     */
    private fun getViewByPosition(pos: Int, listView: ListView): View? {
        val firstListItemPosition = listView.firstVisiblePosition
        val lastListItemPosition = firstListItemPosition + listView.childCount - 1
        return if (pos < firstListItemPosition || pos > lastListItemPosition) {
            listView.adapter.getView(pos, null, listView)
        } else {
            val childIndex = pos - firstListItemPosition
            listView.getChildAt(childIndex)
        }
    }

    /**
     * 通过文件路径直接修改文件名
     *
     * @param filePath    需要修改的文件的完整路径
     * @param newFileName 需要修改的文件的名称
     * @return
     */
    private fun FixFileName(filePath: String, newFileName: String): String? {

        var newFileName: String? = newFileName
        val f = File(filePath)
        if (!f.exists()) { // 判断原文件是否存在（防止文件名冲突）
            return null
        }
        newFileName = newFileName!!.trim { it <= ' ' }
        if ("" == newFileName || newFileName == null) // 文件名不能为空
            return null
        var newFilePath: String? = null
        newFilePath = if (f.isDirectory) { // 判断是否为文件夹
            filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName
        } else {
            (filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName
                    + filePath.substring(filePath.lastIndexOf(".")))
        }
        val nf = File(newFilePath)
        try {
            f.renameTo(nf) // 修改文件名
        } catch (err: java.lang.Exception) {
            err.printStackTrace()
            return null
        }
        return newFilePath
    }

    /**
     * 批量删除
    * */
    fun fileDel(dir: String){

    }

    /**
     * 检测列表勾选的成员路径名字,以字串数组的形式返回
     * */
    private fun ItemIsCheck(): List<String> {
        var checkList: List<String>

        checkList=ArrayList()

        if (!itemsList!!.isEmpty()) {
            for (i in 0 until itemsList!!.size) {

                val holder: MyAdapter.ViewHolder = getViewByPosition(i, listView)!!.tag as MyAdapter.ViewHolder
                if(holder.check!!.isChecked)
                    checkList.add(pathList!!.get(i))
//                Log.i("testcheck()", holder.check?.isChecked.toString())
            }
        }
        return checkList
    }

    fun testcheck(view: View){

        if (ItemIsCheck().size != 1) {
            Toast.makeText(this, "只允许重命名单个文件！", Toast.LENGTH_SHORT).show()
            return
        }else{
//            Log.i("testcheck()", ItemIsCheck().size.toString())
            /*val filename=ItemIsCheck().get(0).substring(ItemIsCheck().get(0).indexOfLast { it == '/' }+1)
            val edt = EditText(this)
            edt.minLines = 3
            edt.setText(filename)
            AlertDialog.Builder(this)
                .setTitle("请输入新的文件名")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(edt)
                .setPositiveButton(
                    "确定"
                ) { arg0,
                    arg1 ->
                    Log.i("testcheck()",edt.text.toString())
                }
                .setNegativeButton("取消", null)
                .show()*/
            Toast.makeText(this, "测试！", Toast.LENGTH_SHORT).show()

            DialogUIUtils.showAlert(
                this,
                "登录",
                "",
                "请输入用户名",
                "请输入密码",
                "登录",
                "取消",
                false,
                true,
                true,
                object : DialogUIListener() {
                    override fun onPositive() {}
                    override fun onNegative() {}
                    override fun onGetInput(input1: CharSequence, input2: CharSequence) {
                        super.onGetInput(input1, input2)
                        showToast("input1:$input1--input2:$input2")
                    }
                }).show()

        }

        //pathList?.count() //获取队列文件个数
        //pathList?.get(3) //获取第4位成员

    }



    fun checkSDcard(): Boolean {
        val sdStutusString = Environment.getExternalStorageState()
        return if (sdStutusString == Environment.MEDIA_MOUNTED) {
            true
        } else {
            false
        }
    }

    companion object {
        private val TAG = FileBrowserActivity::class.simpleName + "--->"
    }
}



/**
 * ContentProvider
https://blog.csdn.net/shaochen2015821426/article/details/79748487
ContentResolver
https://blog.csdn.net/qq_32555215/article/details/80169274


 按键按下效果
https://blog.csdn.net/qq_30546585/article/details/82223789


 修改文件名
https://www.cnblogs.com/httpc/p/8384869.html

//目前样式较丑,需要改成自定义样式
//https://blog.csdn.net/sinat_38239454/article/details/79779392
//https://blog.csdn.net/gongyong666/article/details/80766211

//导入aar
/home/zhanghj/work/android_app/jjdxm_dialogui-master/jjdxm-dialogui/build/outputs/aar/jjdxm-dialogui-release.aar

  */